/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package treeship.core.service.xml;

import java.util.List;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import treeship.core.service.Constants;

/**
 *
 * @author Moonchild
 */
public class NodeWrapper {

    private Node node;

    public NodeWrapper(Node node) {
        assert node != null;

        this.node = node;
    }

    public List<NodeWrapper> getChildren() {
        NodeList listProperty = node.getChildNodes();

        return XMLReader.getListOfNodeWrappers(listProperty);

//        List<NodeWrapper> li = new ArrayList<NodeWrapper>();
//        for (int i = 0; i < listProperty.getLength(); i++) {
//            Node item = listProperty.item(i);
//            if (item.getNodeType() == Node.ELEMENT_NODE) {
//                li.add(new NodeWrapper(item));
//            }
//        }
//        return li;
    }

    public boolean hasAttribute(String attrName) {
        Node namedItem = node.getAttributes().getNamedItem(attrName);
        if (namedItem != null) {
            return true;
        }
        return false;
    }

    public NodeWrapper getChild(String childname) {
        for (NodeWrapper nod : getChildren()) {
            if (nod.getName().equals(childname)) {
                return nod;
            }
        }
        return null;
    }

    public String getAttribute(String attrName) {
        Node namedItem = node.getAttributes().getNamedItem(attrName);
        String nome = namedItem.getNodeValue();
        return nome;
    }

    public double getAttributeAsDouble(String attrName) {
        return Double.parseDouble(getAttribute(attrName));
    }

    public long getAttributeAsLong(String attrName) {
        return Long.parseLong(getAttribute(attrName));
    }

    public boolean getAttributeAsBoolean(String attrName) {
        return Boolean.parseBoolean(getAttribute(attrName));
    }

    public double getAttributeAsDoubleWithDefault(String attrName, double deflt) {
        if (hasAttribute(attrName)) {
            return getAttributeAsDouble(attrName);
        }
        return deflt;
    }

    public String getName() {
        return node.getNodeName();
    }

    public String getValue() {
        return node.getTextContent();
    }

    public double getValueAsDouble() {
        return Double.parseDouble(getValue());
    }

    public long getValueAsLong() {
        return Long.parseLong(getValue());
    }

    public boolean getValueAsBoolean() {
        if (getValue().equals(Constants.TRUE)) {
            return true;
        } else if (getValue().equals(Constants.FALSE)) {
            return false;
        } else {
            throw new UnsupportedOperationException();
        }
    }
}
